<template>
	<el-card>
		<template #header>
			<el-form :inline="true">
				<el-form-item label="用户名">
					<el-input v-model="username" placeholder="请输入用户名" clearable/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getList">查询</el-button>
				</el-form-item>
			</el-form>
		</template>
		<el-table
			:data="list"
			border
			style="width: 100%">
			<el-table-column type="index" width="80" align="center"/>
			<el-table-column prop="username" label="用户名" align="center">
				<template #default="{row}">
					<span v-if="!row.isEdit">{{row.username}}</span>
					<el-input v-else v-model="currentRow.username"/>
				</template>
			</el-table-column>
			<el-table-column label="权限" align="center">
				<template #default="{row}">
					<template v-if="!row.isEdit">
						<el-tag v-if="row.is_admin === 1" type="success">管理员</el-tag>
						<el-tag v-else type="info">普通用户</el-tag>
					</template>
					<el-switch v-else v-model="currentRow.is_admin" :active-value="1" :inactive-value="0" active-text="管理员" inactive-text="普通用户"/>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="180" align="center">
				<template #default="scope">
					<el-button type="primary" :disabled="currentUser.id == scope.row.id" size="small" @click="openHandel(scope.row)" v-if="!scope.row.isEdit">编辑</el-button>
					<el-button type="success" :disabled="currentUser.id == scope.row.id" size="small" @click="save" v-else>保存</el-button>
					<el-button type="danger" :disabled="currentUser.id == scope.row.id" size="small" @click="deleteHandel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
	</el-card>
</template>
<script setup>
import {listApi, updateApi, delUserApi} from '@/api/user.js'
import {reactive, ref, computed} from "vue";
import {useUserStore} from '@/stores/user.js'
import {ElMessage, ElMessageBox} from "element-plus";
import useMessage from "@/utils/useMessage.js";

const store = useUserStore()

const currentUser = computed(()=> {
	return store.user
})

const list = ref([])

const currentRow = ref({
	id: '',
	username: '',
	is_admin: ''
})

const username = ref('')

const getList = async ()=> {
	const res = await listApi(username.value)
	list.value = res.data.map(item=>{
		return {
			...item,
			isEdit: false
		}
	})
}
getList()

const openHandel = (row)=> {
	currentRow.value = row;
	row.isEdit = row
}

const save = async ()=> {
	const res = await updateApi({
		id: currentRow.value.id,
		username: currentRow.value.username,
		is_admin: currentRow.value.is_admin
	})
	if(res.code === 200){
		getList()
	}
	useMessage(res)
}

const deleteHandel = async (row)=> {
	const confirm = await ElMessageBox.confirm('确定删除吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
	if (confirm){
		const res = await delUserApi(row.id)
		if(res.code === 200) {
			getList()
		}
		useMessage(res)
	}
}
</script>
<style scoped>

</style>
